package controller

import (
	"ez/apps/uc/auto/controller"
	uc "ez/apps/uc/document"
	"ez/config/code"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
)

type UcacheController struct {
	controller.UcacheAutoController
}

func init() {
	c := &UcacheController{}
	c.SetRouteParam("/uc", "/admin", "Ucache")
	ez.CreateApi(c.AdminGet(), c.GetAction).SetRouterName("[uc]用户缓存_创建")
	ez.CreateApi(c.AdminList(), c.ListAction).SetRouterName("[uc]用户缓存_列表")
	ez.CreateApi(c.AdminSave(), c.SaveAction).SetRouterName("[uc]用户缓存_保存")
	ez.CreateApi(c.AdminCopy(), c.CopyAction).SetRouterName("[uc]用户缓存_复制")
	ez.CreateApi(c.AdminUpdate(), c.UpdateAction).SetRouterName("[uc]用户缓存_更新")
	ez.CreateApi(c.AdminChoice(), c.ChoiceAction).SetRouterName("[uc]用户缓存_选项")
	ez.CreateApi(c.AdminDelete(), c.DeleteAction).SetRouterName("[uc]用户缓存_删除")
	ez.CreateApi(c.AdminUnDelete(), c.UnDeleteAction).SetRouterName("[uc]用户缓存_恢复")
	ez.CreateApi(c.AdminDestroy(), c.DestroyAction).SetRouterName("[uc]用户缓存_销毁")
	ez.CreateApi(c.AdminUpdateMany(), c.UpdateManyAction).SetRouterName("[uc]用户缓存_更新_批量")
	ez.CreateApi(c.AdminDeleteMany(), c.DeleteManyAction).SetRouterName("[uc]用户缓存_删除_批量")
	ez.CreateApi(c.AdminDestroyMany(), c.DestroyManyAction).SetRouterName("[uc]用户缓存_销毁_批量")
	ez.CreateApi(c.Api("/_uc_get"), c.UcGetAction).SetRouterName("[uc]用户缓存_获取")
	ez.CreateApi(c.Api("/_uc_set"), c.UcSetAction).SetRouterName("[uc]用户缓存_设置")
}

// func (c UcacheController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c UcacheController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c UcacheController) ListAction(session *ez.Session) { /* 在这里面重构 */ }

var crud *uc.UcacheCrud

func init() {
	crud = uc.NewUcacheCrud()
}

func (c UcacheController) UcSetAction(session *ez.Session) {
	this := cc.New(session)
	uid := this.GetUserId()
	if uid == 0 {
		this.ReturnError(code.ErrorAuth, "登录超时", "")
		return
	}
	key := this.Get("key").IsString()
	data := this.Get("data").IsMap()
	find, _ := crud.FindOneBy(ss.M{"uid": uid, "key": key}, nil)
	if find.Id == 0 {
		find.Key = key
		find.Uid = uid
	}
	find.Data = data
	_ = find.Save()

	this.ReturnSuccess("OK", find.Data)
}

func (c UcacheController) UcGetAction(session *ez.Session) {
	this := cc.New(session)
	uid := this.GetUserId()
	if uid == 0 {
		this.ReturnError(code.ErrorAuth, "登录超时", "")
		return
	}
	key := this.Get("key").IsString()
	find, _ := crud.FindOneBy(ss.M{"uid": uid, "key": key}, nil)
	this.ReturnSuccess("OK", find.Data)
}
